package com.bghx.bghxmvc.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bghx.bghxmvc.form.ActionForm;
import com.bghx.bghxmvc.form.FillForm;
import com.bghx.bghxmvc.vo.XmlBean;


public class ActionServlet extends HttpServlet {

	
	private static final long serialVersionUID = 1L;
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		
		String path = this.getPath(request.getServletPath());
		
		@SuppressWarnings("unchecked")
		Map<String,XmlBean> map = (Map<String, XmlBean>) this.getServletContext().getAttribute("bghxmvc-config");
		XmlBean xml = map.get(path);
		String formClass = xml.getFormClass();
		ActionForm form = FillForm.fill(request, formClass);
		String actionClass = xml.getActionClass();
		Action action = null;
		String url = "";
		try{
			Class clazz = Class.forName(actionClass);
			action = (Action) clazz.newInstance();
			url = action.execute(request,response, form, xml.getForwardMap());
		}catch(Exception e){
			System.out.println("严重：控制器异常！");
		}
		
		RequestDispatcher dis = request.getRequestDispatcher(url);
		dis.forward(request, response);
	}	
	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			this.doGet(request, response);
	}	

	private String getPath(String path){
		return path.split("\\.")[0];
	}	
	
}
